package com.qing.utils.lottery.dlt;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.qing.utils.lottery.dlt.entity.DltQueryResponse;
import com.qing.utils.lottery.ssq.bean.SsqResponse;

import java.io.File;
import java.nio.charset.StandardCharsets;

public class DltQueryUtil {

    private static String url = "https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry?gameNo=85&provinceId=0&isVerify=1&pageNo=1&pageSize=" + 30000;

    public static void main(String[] args) {
        DltQueryResponse ssqResponse = querySsqWinningList(10000);
        System.out.println(JSONUtil.toJsonPrettyStr(ssqResponse));

        System.out.printf("大乐透pageCount=[%s], countNum=[%s], resultSize=[%s]%n", ssqResponse.getValue().getPages(), ssqResponse.getValue().getPageNo(), ssqResponse.getValue().getList().size());
        saveSsqData(ssqResponse);
    }


    private static DltQueryResponse querySsqWinningList(int count) {
//        String ssqQueryUrl = "http://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&issueStart=&issueEnd=&dayStart=&dayEnd=&issueCount="+10000;
//        String ssqQueryUrl = "http://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&issueStart=&issueEnd=&dayStart=&dayEnd=&pageNo=1&pageSize=30&systemType=PC&issueCount=" + count;
        String s = HttpUtil.get(url);
        HttpRequest httpRequest = HttpUtil.createGet(url).contentType(ContentType.JSON.getValue());
        System.out.println("============大乐透");
        String body;
        try (HttpResponse response = httpRequest.execute()) {
            body = response.body();
//            System.out.println(body);
            System.out.println("============大乐透");
            DltQueryResponse ssqResponse = JSONUtil.toBean(body, DltQueryResponse.class);
            return ssqResponse;
        }
    }


    private static void saveSsqData(DltQueryResponse ssqResponse) {
        String rootPath = "D:\\Mine\\MySpaces\\Gitee\\common-utils\\lottery-utils\\src\\main\\resources";
        String dir = "dltResponse";
        File dataDir = new File(rootPath, dir);
        if (!dataDir.exists()) {
            boolean mkdir = dataDir.mkdir();
            int tryCount = 10;
            while (!mkdir && tryCount-- > 0) {
                mkdir = dataDir.mkdir();
            }
        }

        String fileName = "dltResponse_" + LocalDateTimeUtil.format(LocalDateTimeUtil.now(), "yyyy-MM-dd_HH_mm_ss");

        FileUtil.writeBytes(JSONUtil.toJsonPrettyStr(ssqResponse).getBytes(StandardCharsets.UTF_8), new File(dataDir, fileName));


    }
}
